package com.chuangsi.project.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangsi.common.exception.ServiceException;
import com.chuangsi.common.utils.SecurityUtils;
import com.chuangsi.project.admin.domain.Agreement;
import com.chuangsi.project.admin.domain.Approve;
import com.chuangsi.project.admin.domain.ApproveConfig;
import com.chuangsi.project.admin.dto.admin.agreement.*;
import com.chuangsi.project.admin.dto.admin.approve.ResAppStatusListDto;
import com.chuangsi.project.admin.dto.common.SelectDto;
import com.chuangsi.project.admin.mapper.AgreementMapper;
import com.chuangsi.project.admin.service.AgreementService;
import com.chuangsi.project.admin.service.ApproveConfigService;
import com.chuangsi.project.admin.service.ApproveService;
import com.chuangsi.project.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 合同模板表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-03-23
 */
@Service
public class AgreementServiceImpl extends ServiceImpl<AgreementMapper, Agreement> implements AgreementService {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ApproveService approveService;
    @Autowired
    private ApproveConfigService approveConfigService;
    @Override
    public List<ResAgreementPageDto> pageQuery(ReqAgreementPageDto req) {
        return  baseMapper.pageQuery(req);
//        LambdaQueryWrapper<Agreement> lambdaQuery = Wrappers.lambdaQuery(Agreement.class);
//        lambdaQuery.like(StrUtil.isNotBlank(req.getAgreementName()), Agreement::getAgreementName, req.getAgreementName());
//        lambdaQuery.eq(StrUtil.isNotBlank(req.getAppStatus()),Agreement::getAppStatus,req.getAppStatus());
//        lambdaQuery.eq(StrUtil.isNotBlank(req.getUserId()),Agreement::getUserId,req.getUserId());
//        lambdaQuery.ge(StrUtil.isNotBlank(req.getStartTime()),Agreement::getCreateTime,req.getStartTime());
//        lambdaQuery.le(StrUtil.isNotBlank(req.getEndTime()),Agreement::getCreateTime,req.getEndTime());
//        return list(lambdaQuery).stream().map(m->{
//            ResAgreementPageDto res = new ResAgreementPageDto();
//            BeanUtils.copyProperties(m,res);
//            res.setNickName(sysUserService.selectNickNameById(m.getUserId()));
//            res.setUserId(m.getUserId());
//            return res;
//        }).collect(Collectors.toList());

    }

    @Override
    public boolean addAgreement(ReqAgreementAddDto req) {

        Agreement agreement = new Agreement();
        BeanUtils.copyProperties(req, agreement);
        agreement.setUserId(SecurityUtils.getUserId());
        save(agreement);
        List<ApproveConfig> addConfig = approveConfigService.list(new LambdaQueryWrapper<ApproveConfig>()
        .eq(ApproveConfig::getType,"1"));
        List<Approve> list = new ArrayList<>();
        for(ApproveConfig i : addConfig){
            Approve approve = new Approve();
            approve.setUserId(i.getUserId());
            approve.setSourceId(agreement.getAgreementId());
            approve.setSort(i.getSort());
            approve.setType("1");
            list.add(approve);
        }
        return approveService.saveBatch(list);
    }

    @Override
    public boolean updateAgreement(ReqAgreementUpdateDto req) {
        Agreement agreement = this.getById(req.getAgreementId());
        if(agreement==null){
            throw new ServiceException("未查询到合同模板");
        }
        BeanUtils.copyProperties(req,agreement);
        return updateById(agreement);
    }

    @Override
    public ResAgreementDetailDto agreementDetail(ReqAgreementDetailDto req) {
        Long userId = SecurityUtils.getUserId();
        Agreement agreement = this.getById(req.getAgreementId());
        if(agreement==null){
            throw new ServiceException("未查询到合同模板");
        }
        ResAgreementDetailDto res = new ResAgreementDetailDto();
        BeanUtils.copyProperties(agreement,res);
        //判断是否该当前用户审批
        List<ResAppStatusListDto> list = approveService.list(new LambdaQueryWrapper<Approve>()
                .eq(Approve::getSourceId,req.getAgreementId())).stream().map(m->{
            ResAppStatusListDto r = new ResAppStatusListDto();
            BeanUtils.copyProperties(m,r);
            return r;
        }).collect(Collectors.toList());
        List<ResAppStatusListDto> now = list.stream().filter(m -> m.getIsPass() == null).sorted(Comparator.comparing(ResAppStatusListDto::getSort)).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(now)) {
            res.setIsMy(now.get(0).getUserId().equals(userId)?"1":"2");
        }
        return res;
    }

    @Override
    public boolean pass(ReqAgreementPassDto req) {
        int agreementCount = count(Wrappers.lambdaQuery(Agreement.class).eq(Agreement::getAgreementId,req.getAgreementId()));
        if(agreementCount == 0){
            throw new ServiceException("未查询到合同模板");
        }
        LambdaUpdateWrapper<Approve> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Approve::getSourceId,req.getAgreementId());
        //wrapper.eq(Approve::getUserId,SecurityUtils.getUserId());
        if("1".equals(req.getAppStatus())){
            throw new ServiceException("该合同已审核，不能修改为未审核");
        }
        if("2".equals(req.getAppStatus())){
            wrapper.set(Approve::getIsPass,"1");
            wrapper.set(Approve::getPassTime, LocalDateTime.now());
        }
        if("3".equals(req.getAppStatus())){
            wrapper.set(Approve::getIsPass,"2");
            wrapper.set(Approve::getPassTime,LocalDateTime.now());
        }
        approveService.update(wrapper);
        int count = approveService.count(new LambdaQueryWrapper<Approve>().eq(Approve::getSourceId,req.getAgreementId()).eq(Approve::getIsPass,"0"));
        if(count == 0){
            LambdaUpdateWrapper<Agreement> wrapper2 = new LambdaUpdateWrapper<Agreement>();
            wrapper2.eq(Agreement::getAgreementId,req.getAgreementId());
            wrapper2.set(Agreement::getAppStatus,req.getAppStatus());
            update(wrapper2);
        }
        return true;
    }

    @Override
    public List<SelectDto> agreementSelect() {
        return list().stream().map(x->new SelectDto(x.getAgreementId(),x.getAgreementName())).collect(Collectors.toList());
    }
}